package es.nadalgoyo.frikiquest.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import es.nadalgoyo.frikiquest.R;
import es.nadalgoyo.frikiquest.TuPierdesActivity;
import es.nadalgoyo.frikiquest.dispatcher.RespuestaDispatcher;
import es.nadalgoyo.frikiquest.vo.RandomVO;
import es.nadalgoyo.frikiquest.vo.VersionVO;

public class Util {

	public static void showErrorMensaje(Activity activity, String mensajeErr,
			final boolean finalize) {
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);

		builder.setMessage(mensajeErr)
				.setCancelable(true)
				.setPositiveButton(R.string.alertButtonOK,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								try {
									if (finalize)
										this.finalize();
								} catch (Throwable e) {
									e.printStackTrace();
								}
							}
						});

		final AlertDialog alert = builder.create();
		alert.show();
	}

	public static void showCondicionMensaje(final Activity activity,
			String mensajeSino, DialogInterface.OnClickListener listener,
			boolean negativeButton) {
		AlertDialog.Builder builder = new AlertDialog.Builder(activity);

		builder = builder.setMessage(mensajeSino).setCancelable(false);
		builder.setPositiveButton(R.string.alertButtonOK, listener);

		if (negativeButton) {
			builder.setNegativeButton("NO",
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
		}

		final AlertDialog alert = builder.create();
		alert.show();
	}

	public static ProgressDialog getProgresoMensaje(Activity activity,
			String mensaje) {
		ProgressDialog dialog = ProgressDialog
				.show(activity, "", mensaje, true);
		dialog.setCancelable(false);
		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		return dialog;
	}

	public static VersionVO getVersion(String version) {
		VersionVO verVO = new VersionVO("0", "0");
		if (!version.equals("0")) {
			String[] split = version.split("\\.");
			verVO.setVersion(split[0]);
			verVO.setSubVersion(split[1]);
		}

		return verVO;
	}

	public static List<RandomVO> getRandomList(List<? extends Object> objects) {
		List<RandomVO> randomList = new ArrayList<RandomVO>();

		for (int i = 0; i < objects.size(); i++) {
			randomList.add(new RandomVO(i + 1, objects.get(i)));
		}

		return randomList;
	}

	public static Object getRandom(List<RandomVO> randoms) throws Exception {
		if (randoms == null || randoms.size() < 1)
			throw new Exception(
					"No existen preguntas cargadas para generar aleatoriamente.");

		Random rnd = new Random(randoms.size() + new Date().getTime());
		return randoms.get(rnd.nextInt(randoms.size())).getObject();
	}

	public static RespuestaDispatcher getNotOk(Activity act, int puntos,
			String tipo) {
		Bundle bundle = new Bundle();
		bundle.putString(TuPierdesActivity.TIPO_PUNTOS, tipo);

		RespuestaDispatcher respuesta = new RespuestaDispatcher(act, bundle,
				RespuestaDispatcher.RESPUESTA_ISNOTOK);
		respuesta.setPuntuacion(puntos);
		return respuesta;
	}

	public static boolean existConnectionToHostFTP() throws Exception {

		URL url = new URL("http://".concat(Constantes.FTP_HOST));

		URLConnection conn = url.openConnection();
		if (conn instanceof HttpURLConnection) {
			HttpURLConnection hconn = (HttpURLConnection) conn;
			hconn.setConnectTimeout(5000);
			try {
				if (hconn.getResponseCode() == 200) {
					hconn.disconnect();
					return true;
				} else {
					hconn.disconnect();
					throw new Exception("Host no encontrado. "
							.concat(String.valueOf(hconn.getResponseCode()))
							.concat(" - ").concat(hconn.getResponseMessage()));
				}
			} catch (SocketTimeoutException e) {
				return false;
			}
		}
		return false;
	}

	public static void copyFile(InputStream in, OutputStream out)
			throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}

	public static boolean existFile(Activity activity, String fileName) {
		try {
			activity.openFileInput(fileName);
		} catch (FileNotFoundException e) {
			return false;
		}
		return true;
	}

}
